#include "gui/sk_surf.h"
#include "sk_common.h"


struct SK_SURF
{
	SK_INT32 m_w;
	SK_INT32 m_h;
	SK_INT32 m_pixelCount;//redundant
	SK_COLORDEF **m_pixels;
};

SK_SURF* SK_SURF_malloc(SK_INT32 w,SK_INT32 h)
{
	SK_INT32 i;
	SK_SURF * o = (SK_SURF *)SK_MEM_malloc(SIZEOF(SK_SURF));
	o->m_w = w;
	o->m_h = h;
	o->m_pixelCount = w * h;
	o->m_pixels = (SK_COLORDEF**)SK_MEM_malloc(SIZEOF(SK_COLORDEF*) * o->m_h);
	for (i = 0 ;i < h ;i ++)
	{
		o->m_pixels[i] = (SK_COLORDEF*)SK_MEM_malloc(SIZEOF(SK_COLORDEF) * o->m_w);
		//init color is black
		SK_MEM_set(o->m_pixels[i],0x0,SIZEOF(SK_COLORDEF) * o->m_w);
	}
	return o;
}

SK_INT32 SK_SURF_getWidth(SK_SURF *o)
{
	return o->m_w;
}
SK_INT32 SK_SURF_getHeight(SK_SURF *o)
{
	return o->m_h;
}
//alpha formula: alpha * (src - dst) / 255 + dst
SK_COLORDEF SK_SURF_alphaMix(SK_COLORDEF srcPixel, SK_COLORDEF dstPixel,SK_BYTE alpha)
{
	SK_COLORDEF resultPixel;
	resultPixel.m_r = alpha * (srcPixel.m_r - dstPixel.m_r) / 255 +dstPixel.m_r;
	resultPixel.m_g = alpha * (srcPixel.m_g - dstPixel.m_g) / 255 +dstPixel.m_g;
	resultPixel.m_b = alpha * (srcPixel.m_b - dstPixel.m_b) / 255 +dstPixel.m_b;
	return resultPixel;
}


void SK_SURF_copy(const SK_SURF * src,const SK_RECT * srcRect,SK_SURF * dst,SK_BYTE alpha)
{
	SK_INT32 i,j;
	for (i = srcRect->top;i <= srcRect->bottom; i++ )
	{
		for (j = srcRect->left; j <= srcRect->right; j++)
		{
			SK_COLORDEF srcPixel = (src->m_pixels)[i][j];
			(dst->m_pixels)[i][j] = SK_SURF_alphaMix(srcPixel,(dst->m_pixels)[i][j],alpha);
		}
	}
	

}


void SK_SURF_free(SK_SURF *o)
{
	if (o)
	{
		if (o->m_pixels)
		{
			SK_INT32 i;
			for (i = 0 ;i < o->m_h ;i++)
			{
				SAFE_FREE((o->m_pixels)[i]);
			}
			SAFE_FREE(o->m_pixels);
		}
		SAFE_FREE(o);
	}
	
}